package com.common.controller;

import cn.hutool.json.JSONObject;
import com.common.authentication.Oauth2ModeAuthentication;
import com.common.config.CommonApplicationConfig;
import com.common.dao.ResourceDao;
import com.common.enums.ApiResult;
import com.common.model.BusinessUserModel;
import com.common.model.SystemApplicationWebModel;
import com.common.mysql.Where;
import com.common.service.BusinessUserService;
import com.common.sevice.SystemApplicationWebService;
import com.common.sevice.impl.SystemApplicationWebServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/v1/resource")
public class ResourceController {

    @Autowired
    private SystemApplicationWebServiceImpl applicationWebService;

    @Autowired
    private CommonApplicationConfig config;

    @Autowired
    private ResourceDao resourceDao;

    @Autowired
    private BusinessUserService businessUserService;

    @GetMapping("/list")
    public ApiResult list() {
        String appId = config.getAppId();
        List<SystemApplicationWebModel> applicationWebModelList = new LinkedList<>();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        List<SystemApplicationWebModel> allWebModelList = applicationWebService.search(Where.build()
                .field("app_id").equal(appId)
                .and()
                .field("del_flag").equal(0))
                .stream()
                .filter(m->{
                    JSONObject extraJsonObject = m.getExtra();
                    Integer webShowFlag = extraJsonObject.getInt("webShowFlag");
                    return 1 == webShowFlag;
                }).collect(Collectors.toList());
        Map<String, SystemApplicationWebModel> webModelMap = allWebModelList.stream()
                .collect(Collectors.toMap(SystemApplicationWebModel::getId, Function.identity()));
        if (authentication instanceof Oauth2ModeAuthentication oauth2ModeAuthentication) {
            Object businessId = oauth2ModeAuthentication.getBusinessId();
            BusinessUserModel businessUserModel = businessUserService.getById((String) businessId);
            if (!ObjectUtils.isEmpty(businessUserModel)){
                String account = businessUserModel.getAccount();
                if ("admin".equals(account)){
                    return ApiResult.success(applicationWebService.buildTree(allWebModelList));
                }
            }
            //查询当前用户所分配的资源
            List<String> resourceIdList = resourceDao.getResourceIdListByUserId(businessId);
            if (!CollectionUtils.isEmpty(resourceIdList)) {
                applicationWebModelList = allWebModelList
                        .stream()
                        .filter(m -> resourceIdList.contains(m.getId()))
                        .collect(Collectors.toList());
            }
        }
        List<SystemApplicationWebModel> resultList = new LinkedList<>();
        if (!CollectionUtils.isEmpty(applicationWebModelList)) {
            for (SystemApplicationWebModel webModel : applicationWebModelList) {
                getParentModel(webModel, webModelMap, resultList);
            }
        }
        return ApiResult.success(applicationWebService.buildTree(resultList));
    }

    private static void getParentModel(SystemApplicationWebModel applicationWebModel, Map<String, SystemApplicationWebModel> webModelMap, List<SystemApplicationWebModel> resultList) {
        resultList.add(applicationWebModel);
        String parentId = applicationWebModel.getParentId();
        if (StringUtils.hasText(parentId) && webModelMap.containsKey(parentId)) {
            getParentModel(webModelMap.remove(parentId), webModelMap, resultList);
        }
    }

}
